package com.tbit.uqbike.tergateway.wa205pkg;

import com.alibaba.fastjson.annotation.JSONField;
import com.tbit.uqbike.TerGatewayMain;
import com.tbit.uqbike.protocol.ATerPkg;
import com.tbit.uqbike.protocol.AnalyzeImpl.AProtocol;
import com.tbit.uqbike.protocol.AnalyzeImpl.WA205DeEnCoder;
import com.tbit.uqbike.tergateway.config.TerGatewayConfig;
import com.tbit.uqbike.tergateway.data.TerGatewayData;
import com.tbit.uqbike.tergateway.entity.AConnInfo;
import com.tbit.uqbike.tergateway.entity.TerTempData;
import com.tbit.uqbike.tergateway.pojo.TerBattery;
import com.tbit.uqbike.tergateway.pojo.TerPos;
import com.tbit.uqbike.tergateway.wa206pkg.PosInfo;
import com.tbit.uqbike.util.*;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * Created by MyWin on 2018/5/22 0022.
 */
public class Pos extends ATerPkg {
    private static Logger logger = LoggerFactory.getLogger(ControlInfo.class);
    public String sn;
    public String lon;
    public String lat;
    public String safeStatus;
    public String batvol;

    @Override
    public void doBusiness() {
        TerTempData terTempData = TerGatewayData.getTerTempDataByMno(this.mno);
        TerPos terLastPos = terTempData.getLastPos();
        // 获取电量对象
        TerBattery terBattery = getTerBattery();
        // 处理电量
        TerGatewayMain.terEvnet.terRecvNewBattery(terTempData, terBattery);

        TerPos newPos = getTerPos();
        Integer code = ErrorCode.OK;
        if (null != newPos) {
            // 判断经纬度合法性
            if (!newPos.isLatlonOk()) {
                code = ErrorCode.ErrorLngLatError;
            } else {
                // 计算里程
                int signMile = 0;
                if (null != terLastPos) {
                    if (terLastPos.isSatellite() && newPos.isSatellite()) {
                        signMile = (int) (TerPubUtil.calculateDistance(terLastPos.getLon(), terLastPos.getLat(), newPos.getLon(), newPos.getLat()) * 1000);
                        // 获取时间
                        int secInv = (int) DateUtil.GetTimeSpanSec(terLastPos.getDt(), newPos.getDt());
                        if (signMile > secInv * 11) {
                            signMile = 0;
                        }
                    }
                }
                newPos.setMile(signMile);
                if (terLastPos == null || newPos.isNewPos(terLastPos)) {
                    // 更新最后状态
                    terTempData.updateStatus(newPos.getDt(), newPos.getCarStatus(), newPos.signalStatus);
                    //TerGatewayData.setTerCarStatus(newPos.getMachineNO(), newPos.getDt(), newPos.getCarStatus(), newPos.signalStatus);
                    if (TerGatewayConfig.LastPosMustSatellite && newPos.isSatellite()) {
                        // 更新内存
                        terTempData.updateLastPos(newPos);
                    }
                }
                // 插入历史轨迹
                TerGatewayData.addTerHisPos(newPos);
                // 推送给公共平台
                TerGatewayMain.getProducer().sendDataToQueue(TerGatewayConfig.posPushRouteKey, PosInfo.getPosPushMsg(newPos));
            }
            if (code != ErrorCode.OK) {
                logger.info(String.format("由于:[%s]过滤掉轨迹:[%s]", ErrorCode.ErrorString(code), newPos.toString()));
            }
        }
    }

    @Override
    public boolean autoRsp() {
        return true;
    }

    @Override
    public ByteBuf getRsp(AConnInfo info, AProtocol protocol) {
        ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer();
        WA205DeEnCoder.getCommRsp(byteBuf, "1");
        return byteBuf;
    }

    @JSONField(serialize = false)
    public TerBattery getTerBattery() {
        TerBattery bat = new TerBattery();
        bat.setMachineNO(this.mno);
        bat.setDt(new Date());
        bat.setBatteryEU((int) (Double.parseDouble(this.batvol) * 1000));
        bat.setSoc(0);
        bat.setBatteryRemaining(0);
        bat.setBatteryRelativelyRemaining((short) 0);
        return bat;
    }

    private TerPos getTerPos() {
        // 先看位置是否有效
        if (this.lat == null || this.lon == null
                || this.lat.isEmpty() || this.lon.isEmpty()
                || "0.0000".equals(this.lat) || "0.0000".equals(this.lon)) {
            return null;
        }
        //int azimuthStateI = Integer.parseInt(azimuthState);
        TerPos terPos = new TerPos();
        //terPos.setDir(azimuthStateI & 0x3f);
        terPos.setDir(0);
        terPos.setDt(new Date());
        terPos.setExData(StringUtil.Empty);
        terPos.setHigh(0);
        terPos.setMachineNO(this.mno);
        terPos.setSpeed(0);
        terPos.setLat(getDDFromDDMM(lat));
        terPos.setLon(getDDFromDDMM(lon));
        terPos.setMile(0);
        terPos.setCarStatus(0);

        terPos.signalStatus = 0;
        terPos.signMile = 0;
        terPos.hallSpeed = 0;

        terPos.setPointType(ConstDefine.POINT_TYPE_GPS);
        return terPos;
    }

    private static Double getDDFromDDMM(String dfStr) {
        String ddStr = dfStr.substring(0, dfStr.length() - 7);
        String mmssStr = dfStr.substring(dfStr.length() - 7, dfStr.length());
        return Double.parseDouble(ddStr) + Double.parseDouble(mmssStr) / 60.0;
    }

    public static void main(String[] args) {
        Double d = Pos.getDDFromDDMM("11856.1254");
        System.out.println(d.toString());
    }
}
